using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Lib.Helper;
using MSIACCSL2.CoaServices;
using MSIACCSL2.CustomerServices;
using WcfService1.DTO;

namespace MSIACCSL2.ViewModels
{
    public class SaldoPiutangViewModel : ViewModelBase
    {
        private CustomerServicesClient CustomerClient;
        private CoaServicesClient coaClient;
        private CoaDTO _coa; 
        public SaldoPiutangViewModel(CoaDTO coa)
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                CustomerClient = new CustomerServicesClient();
                coaClient = new CoaServicesClient();
            }

            _coa = coa;
            SaldoAwalPiutangs = new ObservableCollection<SaldoAwalPiutang>();
            SaldoAwalPiutangs.Add(new SaldoAwalPiutang());
        }

     

        private ObservableCollection<SaldoAwalPiutang> _SaldoAwalPiutangs;

        public ObservableCollection<SaldoAwalPiutang> SaldoAwalPiutangs
        {
            get { return _SaldoAwalPiutangs; }
            set
            {
                if (ReferenceEquals(_SaldoAwalPiutangs,value) || value==null)return;
                LoadCustomer();
                _SaldoAwalPiutangs = value;
                FirePropertyChanged("SaldoAwalPiutangs");
            }
        }


        public void LoadCustomer()
        {
            CustomerClient.GetAllCustomerCompleted += CustomerClient_GetAllCustomerCompleted;
            CustomerClient.GetAllCustomerAsync();
        }

        void CustomerClient_GetAllCustomerCompleted(object sender, GetAllCustomerCompletedEventArgs e)
        {
            CustomerClient.GetAllCustomerCompleted -= CustomerClient_GetAllCustomerCompleted;
            foreach (var saldoAwalPiutang in SaldoAwalPiutangs)
            {
                saldoAwalPiutang.Customers = e.Result;
                if (saldoAwalPiutang.Customer != null)
                    saldoAwalPiutang.Customer =
                        e.Result.FirstOrDefault(x => x.CustomerId == saldoAwalPiutang.Customer.CustomerId);
            }
        }

        public void SaveSaldoAwalPiutang()
        {
            coaClient.SaveSaldoAwalPiutangCompleted += coaClient_SaveSaldoAwalPiutangCompleted;
            foreach (var saldoAwalPiutang in SaldoAwalPiutangs)
                saldoAwalPiutang.Coa = _coa;
            coaClient.SaveSaldoAwalPiutangAsync(SaldoAwalPiutangs);
        }

        void coaClient_SaveSaldoAwalPiutangCompleted(object sender, AsyncCompletedEventArgs e)
        {
            coaClient.SaveSaldoAwalPiutangCompleted -= coaClient_SaveSaldoAwalPiutangCompleted;
            EventAggregator.PublishMessage("SaveSaldoAwalPiutangFinished",SaldoAwalPiutangs.Sum(x=>x.Saldo));
        }
    }
}